import editNews from '../../api/editNews'
import label from '../../api/label'
import * as types from '../mutation-types'

const state = {
  message: [],
  tags: []
}

const getters = {
  msg: state => state.message,
  tags: state => state.tags
}

const actions = {
  postNews ({ commit }, { params }) {
    return new Promise((resolve, reject) => {
      editNews.postNews(params)
      .then(data => {
        commit(types.ADDNEWS, data.data)
        resolve()
      })
      .catch(err => {
        commit(types.ERREDIT, err)
      })
    })
  },
  getAllTags ({commit}) {
    return new Promise((resolve, reject) => {
      label.getLabelDatas()
      .then(data => {
        commit(types.ALLTAGS, data)
        resolve()
      })
      .catch(err => {
        commit(types.ERREDIT, err)
      })
    })
  }
}

const mutations = {
  [types.ADDNEWS] (state, data) {
    state.message.push({state: 'success', msg: data.message})
  },
  [types.ERREDIT] (state, err) {
    state.message.push({state: 'fail', msg: err})
  },
  [types.ALLTAGS] (state, data) {
    state.tags = data
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
